package com.gmall.common.util;

import com.aliyun.oss.OSSClient;
import org.apache.commons.lang3.StringUtils;
import org.junit.Assert;

/**
 * @author hl.wu
 */
public class OSSUtil {

    /**
     * 获取ossClient
     *
     * @return
     */
    public static OSSClient init(String bucketName, String endpoint, String accessKeyId, String accessKeySecret) {
        Assert.assertNotNull(bucketName);
        Assert.assertNotNull(endpoint);
        Assert.assertNotNull(accessKeyId);
        Assert.assertNotNull(accessKeySecret);
        return new OSSClient(endpoint, accessKeyId, accessKeySecret);
    }

    /**
     * 释放ossClient资源
     */
    public static void shutDown(OSSClient ossClient) {
        ossClient.shutdown();
    }

    /**
     * @param newFileName 生成后的url
     * @return
     */
    public static String getUrl(String newFileName, String bucketName, String endpoint) {
        Assert.assertNotNull(newFileName);
        return new StringBuffer(bucketName).append(".").append(endpoint)
                .append("/").append(newFileName).toString();
    }

    /**
     * @param fileName 生成新的fileName
     * @return
     */
    public static String getFileName(String fileName) {
        Assert.assertNotNull(fileName);
        if (fileName.lastIndexOf(".") > -1) {
            String fileType = StringUtils.substringAfterLast(fileName, ".");
            return UUIDUtils.UUID() + "." + fileType;
        }
        return UUIDUtils.UUID() + fileName;
    }
}